<?php

class Model_Main extends Model
{
	public function get_post()
	{	
		if( isset($_GET['post']) )
		{
			$post_num=(int)$_GET['post'];
			$getpost = $this->getRow("select * from photos_list where id = ?;", $post_num);
			return $getpost;
		}
	}

	public function get_data()
	{	
		$arraypush = array();
		
		//connection method
		$link=$this->connect_to_db();

		// Paginator values calculate
		$max_id_q = mysqli_query($link, "select max(id) from photos_list; ");
		$max_id = mysqli_fetch_array($max_id_q,  MYSQLI_ASSOC);

		if(isset($_COOKIE['view']) and $_COOKIE['view']=='List')
			$step=$_COOKIE['view_n'];
		else $step = 15;

		/* calc number of all pages for paginator
			- $skip: number of current page
			- $step: number of photos at one page
			- $number_of_pages: calc number of all pages */

		if(isset($_GET['page']))
			$skip=((int)$_GET['page'] - 1) * $step;
		else $skip=0;

		
		if($max_id['max(id)'] % $step == 0)
			$number_of_pages=intval($max_id['max(id)'] / $step) ;
		else
			$number_of_pages = intval($max_id['max(id)'] / $step) +1;

		//select photos and tags
		$q_skip = mysqli_query($link, " 
			select p.id,p.page_number,p.photo_filename, 
				GROUP_CONCAT(DISTINCT t.tag order by t.tag asc separator ', ') as tags 
			from photos_list as p 
			left join photo_tags as t 
				on p.id = t.photo_id group by p.id desc limit $skip, $step;
		");


		while($skip_photo = mysqli_fetch_array($q_skip, MYSQLI_ASSOC))
			array_push($arraypush, 
						array(
						'Id' => $skip_photo['id'],
						'PageNumber' => $skip_photo['page_number'],
						'PhotoFilename' => $skip_photo['photo_filename'],
						'Tag' => $skip_photo['tags']
						)
				);


		$arraypaginator = array(
			'NumOfPages' => $number_of_pages,
			'Step' => $skip/$step+1);

		mysqli_close($link);
		
		return array($arraypush, $arraypaginator);
	}

}
